package com.crois.barrier.web.plugin.post;

import com.alibaba.fastjson.JSONObject;
import com.crois.barrier.common.dto.ApiRouteInfo;
import com.crois.barrier.common.dto.LogSend;
import com.crois.barrier.common.enums.PluginEnum;
import com.crois.barrier.common.enums.PluginTypeEnum;
import com.crois.barrier.plugin.BarrierPluginChain;
import com.crois.barrier.web.cache.CacheManager;
import com.crois.barrier.web.log.LogSendSvc;
import com.crois.barrier.web.plugin.AbstractBarrierPlugin;
import com.crois.barrier.web.support.ServerWebExchangeUtils;
import com.zhimydou.cloud.common.resp.ApiResponse;
import com.zhimydou.ztools.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import org.reactivestreams.Publisher;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.util.MultiValueMap;
import reactor.core.publisher.Flux;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author Hou Ze Yu
 * @description 日志插件
 * @date 2020/5/7
 */
@Slf4j
public class LogPlugin extends AbstractBarrierPlugin {


    private static final String START_TIME = "startTime";


    private CacheManager cacheManager;

    private LogSendSvc logSendSvc;

    Logger LOGGER = LoggerFactory.getLogger(LogPlugin.class);

    public LogPlugin(CacheManager cacheManager,LogSendSvc logSendSvc) {
        super(cacheManager);
        this.cacheManager = cacheManager;
        this.logSendSvc = logSendSvc;
    }

    @Override
    public PluginTypeEnum pluginType() {
        return PluginTypeEnum.POST;
    }

    @Override
    public String name() {
        return PluginEnum.LOG.getName();
    }

    @Override
    public int order() {
        return PluginEnum.LOG.getCode();
    }

    @Override
    public Boolean skip(ServerWebExchange exchange) {
        //
        ApiRouteInfo routeInfo = (ApiRouteInfo) exchange.getAttributes().get(ServerWebExchangeUtils.BARRIER_ROUTE_ATTR);
        if (CollectionUtil.isNotEmpty(routeInfo.getPlugins())) {
            return !routeInfo.getPlugins().contains(PluginEnum.LOG.getName());
        } else {
            return true;
        }
    }

    @Override
    protected Mono<Void> doExecute(ServerWebExchange exchange, BarrierPluginChain chain, ApiRouteInfo routeInfo) {
        // 执行 监控 操作
        LOGGER.info("[开始执行：LogPlugin]");
        try {
        // 获取请求 信息
        String method = exchange.getRequest().getMethod().name();
        String host = exchange.getRequest().getURI().getHost();
        String path = exchange.getRequest().getURI().getPath();
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        //获取response的 返回数据
        ServerHttpResponse originalResponse = exchange.getResponse();
        exchange.getAttributes().put(START_TIME, System.currentTimeMillis());
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        HttpStatus statusCode = originalResponse.getStatusCode();
        if (statusCode == HttpStatus.OK) {
            if (!path.equals("/")) {
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                        return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                            Long startTime = exchange.getAttribute(START_TIME);
                            Long executeTime = 0L;
                            if (startTime != null) {
                                executeTime = (System.currentTimeMillis() - startTime);
                            }
                            //最重要的是这里，网上有很多对gateway响应进行修改的
                            //但是我这里会进行截断（并不是每次都截）
                            //刚开始也是按照buffer一个一个读，
                            // 然后看了下api 发现可以获取出所有流的集合
                            // 然后又继续查api 发现  DataBufferFactory 可以进行合并多个流的集合
                            //然后就把这个问题解决了。
                            DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                            DataBuffer join = dataBufferFactory.join(dataBuffers);
                            byte[] content = new byte[join.readableByteCount()];
                            join.read(content);
                            //释放掉内存
                            DataBufferUtils.release(join);
                            String responseData = new String(content, StandardCharsets.UTF_8);
                            //responseData就是下游系统返回的内容,可以查看修改
                            ApiResponse apiResponse = JSONObject.parseObject(responseData, ApiResponse.class);
                             // 请求日志
                             log.info("响应内容: host: {}, path: {}, method: {},param:{}, time: {} ms, code:{},message:{},data:{}",host,path,method,queryParams,executeTime,apiResponse.getCode(),apiResponse.getMessage(),apiResponse.getData());
                             logSendSvc.sendLog(JSONObject.toJSONString(new LogSend(host,path,method,JSONObject.toJSONString(queryParams),executeTime,apiResponse.getCode(),apiResponse.getMessage(),JSONObject.toJSONString(apiResponse.getData()))));
                            byte[] uppedContent = new String(responseData.getBytes(), Charset.forName("UTF-8")).getBytes();
                            return bufferFactory.wrap(uppedContent);
                        }));
                    }
                };
                return chain.execute(exchange.mutate().response(decoratedResponse).build());
            }
        }
        return chain.execute(exchange);
    } catch(Exception e){
        log.error(" LogPlugin 異常", e);
        return chain.execute(exchange);
    }
}

}
